package leetcode;

/**
 * @Project : algorithm-learning-java
 * @Package : leetcode
 * @Author : Ruoyu Wang
 * @User : Momenta
 * @DateTime : 2024/1/5 16:43
 */
public class Q0067 {
    public String addBinary(String a, String b) {
        StringBuilder res = new StringBuilder();
        StringBuilder sa = new StringBuilder(a);
        StringBuilder sb = new StringBuilder(b);
        sa.reverse();
        sb.reverse();

        int c = 0;
        int k = 0;
        for (; k < a.length() && k < b.length(); k++) {
            int sum = sa.charAt(k) - '0' + sb.charAt(k) - '0' + c;
            res.append(sum % 2);
            c = sum >> 1;
        }

        for (; k < a.length(); k++) {
            int sum = sa.charAt(k) - '0' + c;
            res.append(sum % 2);
            c = sum >> 1;
        }
        for (; k < b.length(); k++) {
            int sum = sb.charAt(k) - '0' + c;
            res.append(sum % 2);
            c = sum >> 1;
        }
        if (c != 0) {
            res.append(c);
        }
        return res.reverse().toString();
    }

    public static void main(String[] args) {
        Q0067 sl = new Q0067();
        System.out.println(sl.addBinary("11", "1"));
    }
}
